package org.jeecg.modules.cascv.image.service.merge.zaixiangui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.databind.ObjectReader;
import com.jeecg.dingtalk.api.core.response.Response;
import jdk.nashorn.internal.ir.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.service.merge.WurongqiService;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;

/**
 * @author;作者
 * @Date 2023/2/7 10:03
 * @Description : 在线柜操作箱 比较复杂。
 * @Version
 */
@Slf4j
@Service
public class ZaixianguiCaozuoxiangService extends ImageService {
    @Value("${imageurl}")
    private  String imageurl;
    @Value("${python.writePicUrl}")
    private String pythonWritePicUrl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {//设备的文件格式描述文件，每个设备吐出来的数据格式 ids格式文件 接口数据
        return "6D1DH_7DH,6D2DH_7BH";
    }


    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }

        String frames_field = LaptopConstant.FRAME_FIELD_MAP.get(idsName);
        String dataFrames = conJson.getString(frames_field);
        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        conJson.remove(frames_field);
        //dataFrames = dataFrames.substring(7,dataFrames.length()-10);
        dataFrames = dataFrames.substring(7,dataFrames.length()-9);
        StringBuilder queue = LaptopConstant.imageData.get(key);

        if(queue != null && queue.length() < 1996 * 2){
            dataFrames = queue.toString() + dataFrames;
            boolean checkStart = false;
            if (dataFrames.contains(LaptopConstant.ZAIXIANGUI_CAOZUOXIANG_HEADER)) { //表示是否包含1acffc1d
                checkStart = true;
            }

            if(checkStart){
                queue = new StringBuilder();
                LaptopConstant.imageData.put(key, queue);
                queue.append(dataFrames);
            }else{
                LaptopConstant.imageData.remove(key);
            }
            return null;
        }
//判断是否包含WURONGQI_HEADER = "1acffc1d"
        if (dataFrames.contains(LaptopConstant.ZAIXIANGUI_CAOZUOXIANG_HEADER)) {
            if(queue != null){
                queue.append(dataFrames);
                if(queue.length() > 1996 * 2){
                    composite(queue, conJson, idsName, key,secondStr,subSecondStr);
                }
            }
            queue = new StringBuilder();
            LaptopConstant.imageData.put(key, queue);
            queue.append(dataFrames);
            return null;
        }

        if (isNeedMergeBehindXuanFu(dataFrames) && queue == null) {//判断dataFrames是否有结尾
            queue = new StringBuilder();
            LaptopConstant.imageData.put(key, queue);
            //Java中的append( )方法其实是创建了一个新的数组，扩大了长度，将需要添加的字符串给复制到这个新的数组中
            //Stringbuffer是动态字符串数组，append( )是往动态字符串数组添加，跟“xxxx”+“yyyy”相当‘+’号
            queue.append(dataFrames);
            return null;
        } else if (queue != null) { //如果queue不是空的那么加上dataFrames
            queue.append(dataFrames);
            return null;
        }

        return null;
    }




    private  boolean composite(StringBuilder sb, JSONObject content, String idsName, String key,String secondStr ,String subSecondStr) {

        boolean removeHeader = false;
        boolean removePre = false;
        //查找WURONGQI_HEADER = "1acffc1d"第一次出现的位置  headerIndex：1acffc1d的位置
        int headerIndex = sb.indexOf(LaptopConstant.ZAIXIANGUI_CAOZUOXIANG_HEADER); //WURONGQI_HEADER = "1acffc1d";
        //截取 headerIndex+8到headerIndex+88的 生成header44Str
        String header44Str = sb.substring(headerIndex - 40, headerIndex + 48);
        int width = Integer.parseInt(header44Str.substring(48, 56), 16);   //截取header44Str的 48-56 然后转换成16进制
        int height = Integer.parseInt(header44Str.substring(56, 64), 16);
        int imageSize = width * height;

        sb.delete(0, headerIndex);

        String headerStr = sb.substring(0, 48);
//        Map<String, String> headerMap = HeaderUtil.parseGaowengui(headerStr);
        sb = sb.delete(0, 48);

        int oneCanSize = 16 + 1472 * 2;

        int headerSize = 16;

        ByteBuffer byteBuf = ByteBuffer.allocate(imageSize);
        int writeIndex = 0;

        int i = 0;

        while (true) {
            if (sb.length() < oneCanSize) {
                break;
            }
            String oneCanStr = sb.substring(0, oneCanSize).trim();
            if (oneCanStr.length() < oneCanSize) {
                break;
            }
            //拿到oneCanStr后，将其从sb中删除
            sb.delete(0, oneCanSize);
            byte[] bytes = new byte[0];
            try {
                bytes = HexUtil.decodeHex(oneCanStr.substring(headerSize));
            } catch (Exception e) {
                e.printStackTrace();
            }
            int writeLen = bytes.length;
            if (writeIndex + writeLen > imageSize) {
                writeLen = imageSize - writeIndex;
                byteBuf.put(ArrayUtil.sub(bytes, 0, writeLen));
            } else {
                byteBuf.put(bytes);
            }
            writeIndex += writeLen;
            if (writeIndex > imageSize) {
                break;
            }
        }

        if (writeIndex < imageSize && sb.length() / 2 > imageSize - writeIndex) {
            String oneCanStr = null;
            try {
                oneCanStr = sb.substring(headerSize, (imageSize - writeIndex) * 2 + headerSize);
                byte[] bytes = HexUtil.decodeHex(oneCanStr);
                byteBuf.put(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
            long start = System.currentTimeMillis();
            if (byteBuf.position() < imageSize) {
                    byte[] arr = new byte[imageSize - byteBuf.position()];
                    Arrays.fill(arr, (byte) 0);
                    byteBuf.put(arr);
                }

                byteBuf.flip();
                byte[] arr = new byte[imageSize];
                if (byteBuf.limit() < imageSize) {
                    System.out.println("长度不足");
                }
                byteBuf.get(arr);

                String idStr = IdWorker.getIdStr();
               //    int png = LaptopConstant.nativeImageIO.write(arr,height,width, "/data/images/", idStr + ".png", "png");

                Future<String> submit = LaptopConstant.python_pool.submit(new Callable<String>() {
                    @Override
                    public String call() {
                        Long randomInt = LaptopConstant.python_loop.getAndAdd(1);
                        String postRes = HttpUtil.post("http://127.0.0.1:9981", HexUtil.encodeHexStr(arr) + ",bggr,"+"png"+"," + height + "," + width + "," +  "/data/images/" + idStr + ".png" + ",1");
                        return postRes;
                    }
                });

                String postRes = null;
                try {
                    postRes = submit.get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(!StringUtils.equalsIgnoreCase(postRes, "ok")){
                    log.error("合成图片失败！");
                }

//        FileUtil.move(new File("/disk1/zaixiangi/" + imageSaveName), new File(imageConfig.getBaseDir() + imageSaveDir + imageSaveName), true);


                String ImagePath = "/data/images"+idStr+".png";

//        // 生成csv 文件
//        String csvFileName = ImagePath.replace("." + "png", ".csv");
//        if (currentImageTask.getZdyMap() != null && !currentImageTask.getZdyMap().isEmpty()) {
//            String[] thStr = new String[currentImageTask.getZdyMap().size()];
//            String[] valStr = new String[currentImageTask.getZdyMap().size()];
//            ObjectReader objectReader = JsonReaderUtil.getReader();
//            try {
//                int i = 0;
//                ObjectNode jsonNode = (ObjectNode) objectReader.readTree(dataJson);
//                for (Map.Entry<String, String> entry : currentImageTask.getZdyMap().entrySet()) {
//                    jsonNode.put(entry.getKey(), entry.getValue());
//                    String[] arr = entry.getValue().split(";");
//                    thStr[i] = arr[2];
//                    valStr[i] = arr[1];
//                    i++;
//                }
//                dataJson = jsonNode.toString();
//            } catch (Exception e) {
//                log.error("拼接csv", e);
//            }
//
//            CsvWriter writer = CsvUtil.getWriter(csvFileName, Charset.forName("gbk"));
//            writer.write(thStr);
//            writer.write(valStr);
//            writer.flush();
//            writer.close();
//        }
                String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
        System.out.println("imageUrl = " + imageUrl);
        content.put("imageUrl", imageUrl);
                content.put("idsName", idsName);
                // String secondStr = content.getString(LaptopConstant.SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                // String subSecondStr = content.getString(LaptopConstant.SUB_SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                String[] split = secondStr.split(":");
                content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        content.put("key", key);
            log.info("在线柜操作箱"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

        return content;
    },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

        return true;
    }

    private boolean isNeedMergeBehindXuanFu(String dataFrames) {
        return dataFrames.endsWith(LaptopConstant.ZAIXIANGUI_CAOZUOXIANG_HEADER_START_SUB_1) //后缀均可以通过endsWith()方法来判断 是的返回true
                || dataFrames.endsWith(LaptopConstant.ZAIXIANGUI_CAOZUOXIANG_HEADER_START_SUB_2)
                || dataFrames.endsWith(LaptopConstant.ZAIXIANGUI_CAOZUOXIANG_HEADER_START_SUB_3)
                ;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("E:\\11图像数据\\cut2\\在线\\T20230412090225_0001_006D_F1_00_6DCD_2024_007D_7D_6D1D_000000000.txt");
        ZaixianguiCaozuoxiangService zaixianguiCaozuoxiangService = new ZaixianguiCaozuoxiangService();
        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            zaixianguiCaozuoxiangService.merge(jsonObject, "6D1DH_7DH", "6D1DH_7DH");
        }

    }
}
